package cn.usian.pricingstrategy.coefficient.service.impl;

import cn.usian.pojo.pricingstrategy.coefficient.PricingSpecialTimeSlot;
import cn.usian.pricingstrategy.coefficient.mapper.TimeSlotMapper;
import cn.usian.pricingstrategy.coefficient.service.ITimeSlotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TimeSlotServiceImpl implements ITimeSlotService {
    @Autowired
    private TimeSlotMapper timeSlotMapper;

    @Override
    public List<PricingSpecialTimeSlot> list() {
        return timeSlotMapper.list();
    }

    @Override
    public String save(List<PricingSpecialTimeSlot> pricingSpecialTimeSlot) {
    log.info("保存特殊时间段, 总数: {}", pricingSpecialTimeSlot.size());

    Set<Long> idsToUpdate = pricingSpecialTimeSlot.stream()
        .filter(item -> item.getId() != null)
        .map(PricingSpecialTimeSlot::getId)
        .collect(Collectors.toSet());

    List<PricingSpecialTimeSlot> existingItems = timeSlotMapper.findByIds(idsToUpdate);

    Map<Long, PricingSpecialTimeSlot> existingMap = existingItems.stream()
        .collect(Collectors.toMap(PricingSpecialTimeSlot::getId, item -> item));

    try {
        for (PricingSpecialTimeSlot item : pricingSpecialTimeSlot) {
            if (item.getId() == null) {
                throw new IllegalArgumentException("ID 不能为空");
            }

            PricingSpecialTimeSlot existingItem = existingMap.get(item.getId());
            if (existingItem != null) {
                timeSlotMapper.update(item);
            } else {
                timeSlotMapper.save(item);
            }
        }
    } catch (Exception e) {
        log.error("保存特殊时间段时发生错误", e);
        return "操作失败";
    }

    return "操作成功";
}


    @Override
    public PricingSpecialTimeSlot findById(long id) {
        return timeSlotMapper.findById(id);
    }

    @Override
    public Integer delete(long id) {
        return timeSlotMapper.delete(id);
    }
}
